#pragma once

#include <iostream>
#include <mutex>
#include <unordered_map>
#include <websocketpp/server.hpp>
#include <websocketpp/config/asio_no_tls.hpp>
#include "log.hpp"
typedef websocketpp::server<websocketpp::config::asio> server;

class online_manager{
public:
    static online_manager* get_online_manager(){
        if(_onlinemanager == nullptr){
            {
                std::unique_lock<std::mutex> lock(_mutex);
                if(_onlinemanager == nullptr){
                    _onlinemanager = new online_manager();
                    return _onlinemanager;
                }
                return _onlinemanager;
            }  
        }
        return _onlinemanager;
 
    }
    void insert_in_gamehall(uint64_t uid,server::connection_ptr con){
        logmessage(DEBUG,"insert_in_gamehall 成功");
        std::unique_lock<std::mutex> mut(_mutex);
        _uid_in_gamehall.insert(std::make_pair(uid,con));
    }
    void insert_in_gameroom(uint64_t uid,server::connection_ptr con){
        std::unique_lock<std::mutex> mut(_mutex);
        _uid_in_gameroom.insert(std::make_pair(uid,con));
    }

    void exit_from_gamehall(uint64_t uid){
        logmessage(DEBUG,"exit_from_gamehall 成功");
        std::unique_lock<std::mutex> mut(_mutex);
        _uid_in_gamehall.erase(uid);
    }
    void exit_from_gameroom(uint64_t uid){
        logmessage(DEBUG,"exit_from_gameroom 成功");
        std::unique_lock<std::mutex> mut(_mutex);
        _uid_in_gameroom.erase(uid);
    }

    bool is_in_gamehall(uint64_t uid){
        auto it = _uid_in_gamehall.find(uid);
        if(it == _uid_in_gamehall.end()){
            return false;
        }
        return true;
    }
    bool is_in_gameroom(uint64_t uid){
        auto it = _uid_in_gameroom.find(uid);
        if(it == _uid_in_gameroom.end()){
            return false;
        }
        return true;
    }

    server::connection_ptr get_connectionptr_from_hall(uint64_t uid){
        std::unique_lock<std::mutex> lock(_mutex);
        auto it = _uid_in_gamehall.find(uid);
        if(it == _uid_in_gamehall.end()){
            return server::connection_ptr();
        }

        return it->second;
    }
    server::connection_ptr get_connectionptr_from_room(uint64_t uid){
        std::unique_lock<std::mutex> lock(_mutex);
        auto it = _uid_in_gameroom.find(uid);
        if(it == _uid_in_gameroom.end()){
            return server::connection_ptr();
        }

        return it->second;
    }


private:
    static online_manager* _onlinemanager;

    static std::mutex _mutex;
    std::unordered_map<uint64_t,server::connection_ptr> _uid_in_gamehall;//uid和con的映射
    std::unordered_map<uint64_t,server::connection_ptr> _uid_in_gameroom;
};

online_manager* online_manager::_onlinemanager = nullptr;
std::mutex online_manager::_mutex;